package bo.gustavo.scrapper.export;

import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;

import bo.gustavo.scrapper.model.AppData;
import bo.gustavo.scrapper.model.Persister;
import bo.gustavo.scrapper.util.DataBaseAccessType;

/**
 * Utility class that converts the scrapped data to JSON
 * 
 * @author Gustavo Vera
 * */
public class JSONConverter {

	public static final String JSON_HEADER = "{ \"aaData\": [";

	public static final String JSON_FOOTER = "] }";

	/**
	 * Main method that generates the json data source for the HTML results
	 * 
	 * @author Gustavo Vera
	 * */
	public static void convertToJSON(String path) {
		List<AppData> appDataList = Persister.getInstance().maskOperations(AppData.class, null, DataBaseAccessType.QUERY);
		List<String> jsonElements = new ArrayList<String>();
		for (AppData app : appDataList) {
			jsonElements.add(app.toJSON());
		}
		FileWriter f = null;
		try {
			f = new FileWriter(path);
			f.write(JSON_HEADER);
			f.write(StringUtils.join(jsonElements, ",\r\n"));
			f.write(JSON_FOOTER);
			f.flush();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				f.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}
